package com.ct.config;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.HostInfo;
import cn.hutool.system.SystemUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.InetAddress;

@Component
@Slf4j
public class ApplicationInitConfig implements CommandLineRunner {

    @Autowired
    private Environment env;

    @Override
    public void run(String... args) throws Exception {
        //内存总量
        BigDecimal total = NumberUtil.roundDown(NumberUtil.div(OshiUtil.getMemory().getTotal(), 1024 * 1024 * 1024), 2);

        //可用内存
        BigDecimal available = NumberUtil.roundDown(NumberUtil.div(OshiUtil.getMemory().getAvailable(), 1024 * 1024 * 1024), 2);

        // 逻辑（超线程）CPU
        int logicalProcessorCount = OshiUtil.getProcessor().getLogicalProcessorCount();

        // 获取JVM当前活动线程数
        int activeThreads = Thread.activeCount();

        // CPU相关信息
        CpuInfo cpuInfo = OshiUtil.getCpuInfo();

        //本地主机的地址
        InetAddress inetAddress = InetAddress.getLocalHost();
        HostInfo hostInfo = SystemUtil.getHostInfo();

        log.info("内存总量:{}G | 使用内存:{}G | 可用内存:{}G", total, available, NumberUtil.sub(total, available));
        log.info("CPU当前等待率:{}% | CPU当前空闲率:{}%", cpuInfo.getWait(), cpuInfo.getFree());
        log.info("CPU核心数:{}", cpuInfo.getCpuNum());
        log.info(StrUtil.format("项目名称:{}", env.getProperty("spring.application.name")));
        if (StrUtil.equals(inetAddress.getHostAddress(), hostInfo.getAddress())) {
            log.info(StrUtil.format("项目请求地址:{}:{}", hostInfo.getAddress(), env.getProperty("server.port")));
        } else {
            log.info(StrUtil.format("项目请求地址:{}:{} | {}:{}", inetAddress.getHostAddress(), env.getProperty("server.port"), hostInfo.getAddress(), env.getProperty("server.port")));
        }
        log.info("project server has started successfully!");
    }
}
